package com.cino.demos.controller.comments;

import com.cino.demos.entity.comment.Comment;
import com.cino.demos.service.CommentService;
import com.cino.demos.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class CommentsController {


     @Autowired
     private CommentService commentService;

    @GetMapping("/list")
    public Result List() {
        return Result.success(commentService.commentList());
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody Comment comment){
        commentService.insert(comment);
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Comment comment){
        commentService.update(comment);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id){
        commentService.deleteById(id);
        return Result.success();
    }

   @GetMapping("/tree")
    public Result Tree(){
       List<Comment> list = commentService.commentList();
       int pid = 0;
       List<Comment> Tree = List2Tree(list, pid);
       return Result.success(Tree);
   }

   private List<Comment> List2Tree(List<Comment> list, Integer pid){
       ArrayList<Comment> children = new ArrayList<>();
       for (Comment comment : list) {
           if (comment.getParentId().equals(pid)){
               comment.setList(List2Tree(list, comment.getId()));
               children.add(comment);
           }
       }
       return children;
   }


   @GetMapping("/stringSplit")
    public Result StringSplit(@RequestParam("id") Integer id){
       Comment comment = commentService.searchById(id);
       String content = comment.getContent();
       String[] strings = content.split(",");
       return Result.success(strings);
   }
}
